package com.demo.edit;

import com.edit.office.CloseOffice;
import com.edit.office.EditOffice;
import com.edit.office.UploadOffice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/edit")
public class EditController {

    @GetMapping("/allow")
    public String allow(@RequestParam("readOnly") String readOnly,@RequestParam("username") String username) {
        //考虑文件并发问题，如果一个文件同时被两个人编辑，最后的文件是最后保存时的文件
        //所以可以根据需要来自行控制并非
        // 推荐使用redis控制并发，
        // 当用户打开时添加一条redis记录用户打开了fileId，表示当前用户有fileId的权限，并设置redis时效，避免异常关闭导致未回调close接口导致的文件锁定
        //代表文件被当前用户占用,避免一个文件被同时打开
        //建议30分钟有效期
        //返回download的请求连接，最好download的的url复杂一点，提高安全性
        return "http://localhost:8080/edit/download?readOnly=" + readOnly+"&username="+username;
    }

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        //获取当前用户
        String username = request.getParameter("username");
        EditOffice editOffice = new EditOffice(request, response);
        //设置当前的用户
        editOffice.setCurrentUsername(username);
        //editOffice保存时回调请求
        //setSavePage不设置则文件为只读，不可上传回服务器
        String readOnly = request.getParameter("readOnly");
        if (readOnly.equals("true")){
            editOffice.setSavePage("http://192.168.1.25:8080/edit/upload", "post");//非必须
        }

        //editOffice关闭时回调请求
        editOffice.setClosingUrl("http://192.168.1.25:8080/edit/close");//非必须
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/d.docx");
        // 参数 文件id，文件名，文件流
        //判断当前用户有fileId的打开权限
        editOffice.open("1", "demo.docx", resourceAsStream);//必须
    }

    @PostMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //重新更新redis有效期30分钟
        //
        //
        UploadOffice uploadOffice = new UploadOffice(request, response);
        System.out.println("fileId:" + uploadOffice.getFileId());
        System.out.println("username:" + uploadOffice.getUsername());
        //判断username用户有fileId文件的上传的权限
        File file = new File("D://tddtt.docx");
        uploadOffice.save(file);

    }

    /**
     * 关闭office时回调的请求
     * 可以自定义关闭download请求的权限
     *
     * @param request
     * @param response
     */
    @PostMapping("/close")
    public void close(HttpServletRequest request, HttpServletResponse response) {
        CloseOffice office = new CloseOffice(request, response);
        System.out.println(office.getFileId());
        System.out.println(office.getUsername());
        //关闭fileId对于的访问权限
        //删除redis的记录，代表关闭文件被当前用户占用
    }

}
